"""
一些工具模块
"""
import xml.dom.minidom
from typing import Optional, List


class ParseXml:
    """dom tree"""
    def __init__(self, config_file):
        print(f"[ParseXml:__init__] config_file={config_file}")
        self.dom = xml.dom.minidom.parse(config_file)
        # 端口int过滤下  没有用 pydantic 过滤 先这样吧
        self.filter_int = lambda x, node_name: int(x) if "port" in node_name else str(x)

    def get_child_nodes_from_node(
            self, child, node=None) -> list:
        if node is None:
            node = self.dom
        child_nodes = node.getElementsByTagName(child)
        if child_nodes:
            return child_nodes

    def parse_one_nodes_text(
            self, node_name, node=None):

        child_nodes = self.get_child_nodes_from_node(node_name, node)

        if child_nodes is not None:
            returns = []

            for each_child in child_nodes:

                returns.append(self.filter_int(each_child.firstChild.data, node_name))
            return returns
        
    def _parse_nodes_attrs(
            self, node_name, attr, node=None) -> Optional[list]:
        """
        解析形如:
            <size value="1" />
            <size value="1" />
            <size value="1" />
            <size value="1" />
            <size value="1" />
            <size value="1" />
            <size value="1" />
        """

        child_nodes = self.get_child_nodes_from_node(node_name, node)
        if child_nodes is not None:
            returns = []
            for each_child in child_nodes:

                returns.append(each_child.getAttribute(attr))

            return returns


if __name__ == '__main__':
    p = ParseXml("./config_comm.xml")

    _node = p.get_child_nodes_from_node("size", p.dom)
    print(p._parse_nodes_attrs("size", "value", _node[0]))
